$(function () {

  mui.init({
    pullRefresh: {
      container: "#refreshContainer", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
      down: {
        auto: true,
        callback: function () {
          setTimeout(function () {
            render()
            mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
          }, 1000)
          $('.all').text('00.00')
          
        } 
      }
    }
  });

  function render() {
    $.ajax({
      url: '/cart/queryCart',
      type: 'get',
      success: function (info) {
        console.log(info)
        if(info.error === 400) {
          location.href = 'login.html?backUrl=' + location.href
        }
        $('.mui-table-view').html(template('tmp', {list: info}))
        
      }
    })
  }


  $('.mui-table-view').on('tap', '.btn_delete', function () {
    var id = $(this).data('id')
    $.ajax({
      url: '/cart/deleteCart',
      type: 'get',
      data: {
        id: id
      },
      success: function (info) {
        console.log(info)
        mui('.mui-scroll-wrapper')
          .pullRefresh()
          .pulldownLoading()
      }
    })
  })

  $('.mui-table-view').on('tap', '.btn_change', function () {
    
    var info = this.dataset
    console.log(info)
    var html = template('tmp2', info)
    
    html = html.replace(/\n/g,'')
    mui.confirm( html, '确认', ['取消','确定'], function(e) {
      if(e.index === 1) {
        var id = info.id
        var size = $('.size span.active').text()
        var num = $('.num input').val()
        $.ajax({
          url: '/cart/updateCart',
          type: 'post',
          data: {
            id: id,
            num : num,
            size : size
          },
          success: function (info) {
            console.log(info)
            mui('.mui-scroll-wrapper')
              .pullRefresh()
              .pulldownLoading()
          }
        })
      }
    })

    $('.size span').on('click',function() {
      $(this).addClass('active').siblings().removeClass('active')
    })
    mui('.mui-numbox').numbox()
  })
  
  $('.mui-table-view').on('change','.check',function() {
    var total = 0
    $('.check:checked').each(function(){
      total += +$(this).data('num') * +$(this).data('price')
    })
    total = total.toFixed(2)
    $('.all').text(total)
    
  })
  
})